package com.bestdata.TD440.datasend;


import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Component;


/**
 * UDP server接收上位机传递过来的数据
 * author: chenfu
 */
@Component
@ConfigurationProperties(prefix = UDPServer.PREFIX)
@DependsOn("springContextHolder")
public class UDPServer implements InitializingBean, DisposableBean,Runnable {
    private Logger logger = LoggerFactory.getLogger(UDPServer.class);

    public static final String PREFIX = "udpserver";


    //人工配置端口
    //@Value("${receive.listenport}")
    private int udpListenPort = 9101;

    //@Value("${receive.listenip}")
    private String udpListenIP = "127.0.0.1";

    private Thread thread;

    @Override
    public void run() {
        Bootstrap bootstrap;
        NioEventLoopGroup acceptGroup;
        Channel channel;

        bootstrap = new Bootstrap();
        acceptGroup = new NioEventLoopGroup();
        bootstrap.group(acceptGroup)
                .channel(NioDatagramChannel.class)
                .option(ChannelOption.SO_BROADCAST, true)
                .handler(new ChannelInitializer<NioDatagramChannel>() {
                    @Override
                    protected void initChannel(NioDatagramChannel ch)
                            throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast(new UDPServerHandler());
                    }
                });

        try {
            channel = bootstrap.bind(udpListenIP, udpListenPort).sync().channel();
            logger.info("UdpServer start success ip:" + udpListenIP + ",port:" + udpListenPort);
            channel.closeFuture().await();
        } catch (Exception e){
            logger.error("UdpServer start failed ip:" + udpListenIP + ",port:" + udpListenPort);
            e.printStackTrace();
        } finally {
            acceptGroup.shutdownGracefully();
        }
    }


    @Override
    public void afterPropertiesSet() throws Exception {

    }

    private UDPServer() {
        this.thread = new Thread(this);
        this.thread.start();
    }


    @Override
    public void destroy(){
    }
}
